﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Core.Extentions;
using System.Web.Security;
using System.Web.Mvc;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;

namespace XSTDZ.ERP.WebApp.Models
{
    /// <summary>
    /// 用户模型
    /// </summary>
    public class UserModel
    {
        public UserModel()
        {
        }
        //初始化管理员
        public void InitAdmin()
        {
            var u = new UserDto { 
                 Id=Guid.Parse(SystemConfig.AdminId),
                  AccountName="Admin",
                   CreateTime=DateTime.Now,
                  CreateID = Guid.Parse(SystemConfig.AdminId),
                 Name = "Admin",
                 Password = "Admin",
                 OrgId = Guid.Empty,
                 DeptId = Guid.Empty,
            };
            IUserService userServiceImpl = ServiceLocator.Instance.GetService<IUserService>();
            if (!userServiceImpl.IsExists("Admin"))
            {
                userServiceImpl.AddUser(u);
            }
        }
        /// <summary>
        /// 根据上下文，获取登陆用户的ID
        /// </summary>
        /// <param name="context">当前上下文</param>
        /// <returns></returns>
        public static Guid GetLoginUserId(HttpContextBase context)
        { 
            Guid loginUserId=Guid.Empty;
            if (context.User.Identity.Name != null && !string.IsNullOrEmpty(context.User.Identity.Name.ToString()))
            {
                var userId = CryptographerLite.Decrypt(context.User.Identity.Name.ToString());
                Guid.TryParse(userId.ToString(), out loginUserId);
            }
            return loginUserId;
        }
        /// <summary>
        /// 获得用户的组织机构ID
        /// </summary>
        /// <param name="userID">用户ID （type:GUID）</param>
        /// <returns></returns>
        public Guid GetUserOrgID(Guid userID)
        {
            IUserService userServiceImpl = ServiceLocator.Instance.GetService<IUserService>();
            return userServiceImpl.GetUserOrg(userID);
        }

        /// <summary>
        /// 绑定用户性别
        /// </summary>
        /// <returns></returns>
        public static List<SelectListItem> GetUserGenderRadio()
        {
            return new List<SelectListItem> { 
                 new SelectListItem{ Text="男", Value="1", Selected=true},
                 new SelectListItem{ Text="女", Value="0"}
               //  new SelectListItem{ Text="保密", Value="2"},
            };
        }
        public static List<SelectListItem> GetUserIsPieceRadio()
        {
            return new List<SelectListItem> { 
                 new SelectListItem{ Text="是", Value="1"},
                 new SelectListItem{ Text="否", Value="0", Selected=true}
            };
        }
       
        public string Login(HttpContextBase context,string userName,string userId)
        {
          
            //创造票据
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,/*userName + "@" + */userId,DateTime.Now, DateTime.Now.AddMinutes(30),false,null);
            //加密票据
            string ticString = userId;
           // string ticString = FormsAuthentication.Encrypt(ticket);
            //输出到客户端
         //   context.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, ticString));
          var n= FormsAuthentication.FormsCookieName;
          // context.Response.Cookies.Add(new HttpCookie(n, ticString));
          var userID = CryptographerLite.Encrypt(userId);
          FormsAuthentication.SetAuthCookie(userID, false);
            //跳转到登录前页面
            var url =context.Request.QueryString["ReturnUrl"];
            if (string.IsNullOrEmpty(url))
            {
                url = System.Configuration.ConfigurationManager.AppSettings["IndexHome"].ToString();
            }
            return url;
           // context.Response.Redirect(url);// (HttpUtility.UrlDecode(url));
        }
      
        /// <summary>
        /// 初始化用户角色(针对客户端的控件操作）
        /// </summary>
        /// <param name="userDto"></param>
        /// <param name="roleString"></param>
        /// <returns></returns>
        public UserDto InitUserRoles(UserDto userDto,string roleString)
        {
            if (!string.IsNullOrEmpty(roleString))
            {
                string[] roles = roleString.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                if (userDto.RoleIds != null)
                {
                    userDto.RoleIds.Clear();
                }
                else
                {
                    userDto.RoleIds = new List<Guid>();
                }
                roles.Each(r =>{
                    var strId = r.Replace(",", "");
                    if (!string.IsNullOrEmpty(strId))
                    {
                        var id = Guid.Parse(strId);
                        if (!id.Equals(Guid.Empty))
                        {
                            userDto.RoleIds.Add(id);
                        }
                    }
                });
            }
            return userDto;
        }

        //修改密码，验证
        public string ValidateUserPassword(string dbPassword,string orgPassword,string newPassword,string confirmPassword)
        {
            if (string.IsNullOrEmpty(orgPassword) || string.IsNullOrEmpty(newPassword) || string.IsNullOrEmpty(confirmPassword))
            {
                return "输入不完整，请确保输入完成！";
            }
            if (newPassword != confirmPassword)
            {
                return "两次输入的新密码不一致！";
            }
            if (orgPassword == newPassword)
            {
                return "原密码和新密码相同！";
            }
            if (dbPassword != orgPassword)
            {
                return "原密码输入错误！";
            }
            return "";
        }
    }
}